package com.doghome.mysb.utils;

import java.util.Date;
import java.util.UUID;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JwtUtil {
	// 密钥
	public static final String SECRET = "ff82854752c9d95afb57290fd7b9025af9ff3ee416c889c3870beacc290ca249";

	//间隔时间 单位分钟
	public static final int INTERVAL = 30;
	
	//生成token
	public static String createToken(Long userID) {
		Date latDate = new Date();
		Date expDate = new Date(latDate.getTime()+INTERVAL*60*1000);
		
		return JWT.create()
				.withJWTId(UUID.randomUUID().toString())
				.withIssuedAt(latDate) //jwt生成的时间
				.withExpiresAt(expDate)//jwt过期的时间
				.withClaim("userID", userID)//向jwt中添加数据，可以添加多个，可被调用多次
				.sign(Algorithm.HMAC256(SECRET));//添加签名
	}
	
	//根据token验证是否有效
	public static DecodedJWT verifyToken(String token) {
		DecodedJWT decodedJwt = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
		return decodedJwt;
	}
	
	//读取jwt中存储数据
	public static Long getUserID(String token) {
		return verifyToken(token).getClaim("userID").asLong();
	}
	
	//获取到期时间
	public static Date getExpires(String token) {
		return verifyToken(token).getExpiresAt();
	}
}
